package com.thprojects.myphotomemories.view.components;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.DbController;
import com.thprojects.myphotomemories.controller.FSController;
import com.thprojects.myphotomemories.model.Album;
import com.thprojects.myphotomemories.model.Photo;

import exception.PhotoSourceNotFoundException;
import exception.SDNotReadyException;

public class AlbumAdapter extends BaseAdapter{
	
	List<Album> mAlbums;
	Context mContext;
	FSController mFsController;
	
	public AlbumAdapter(List<Album> albums, Context context){
		mAlbums = albums;
		mContext = context;
		mFsController = FSController.getFSController(context);
	}

	public int getCount() {
		return mAlbums.size();
	}

	public Object getItem(int position) {
		return mAlbums.get(position);
	}

	public long getItemId(int position) {
		return mAlbums.get(position).getId();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.album_big, parent, false);
		Album a = mAlbums.get(position);
		
		Gallery.LayoutParams glp = new Gallery.LayoutParams(Gallery.LayoutParams.WRAP_CONTENT, Gallery.LayoutParams.WRAP_CONTENT);
		v.setLayoutParams(glp);
		
		TextView mName = (TextView) v.findViewById(R.id.album_name_preview);
		mName.setText(a.getName());
		
		ImageView mImage = (ImageView) v.findViewById(R.id.album_img_preview);
		
		
		DbController db = DbController.getDbController(mContext);
		Photo p = db.getAPhotoFromAlbum(a);
		Log.d("MPM", "photo: "+p);
		if (p!=null){
			Bitmap img;
			try {
				img = mFsController.decodeSampledBitmap(p.getPath(), 160, 160);
				mImage.setImageBitmap(img);
			} catch (PhotoSourceNotFoundException e) {
			} catch (SDNotReadyException e) {
			}
		}
		
		
		return v;
	}

}
